package cn.com.jenson.service.auth.filter;

import cn.com.jenson.entity.user.User;
import cn.com.jenson.exception.TokenException;
import cn.com.jenson.service.user.repository.UserRepository;
import cn.com.jenson.service.user.service.UserService;
import cn.com.jenson.system.CommonName;
import cn.com.jenson.util.JWTUtil;
import cn.com.jenson.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 自定义jwt登录
 */
public class JwtAuthFilter extends BasicAuthenticationFilter implements Filter {

    public static final String TOKEN = "Token";
    private final UserRepository userRepository;

    @Resource
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    public JwtAuthFilter(AuthenticationManager authenticationManager, UserRepository userRepository) {
        super(authenticationManager);
        this.userRepository = userRepository;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        setAuth(request.getHeader(TOKEN), request, response);
        chain.doFilter(request, response);
    }


    private void setAuth(String token, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (StringUtil.isEmpty(token)) {
            return;
        }
        HashMap<String, String> tokenHashMap = JWTUtil.getContext(token);
        if (Objects.isNull(tokenHashMap.get("userId")) || Objects.isNull(tokenHashMap.get("timeState")))
            doException(request, response);
        long timeState = Long.parseLong(tokenHashMap.get("timeState"));
        if (System.currentTimeMillis() > timeState) {
            doException(request, response);
        }
        Integer id = Integer.valueOf(tokenHashMap.get("userId"));
        UsernamePasswordAuthenticationToken userAsToken = new UsernamePasswordAuthenticationToken(id, null);
        SecurityContextHolder
                .getContext()
                .setAuthentication(
                        userAsToken
                );
    }

    private void doException(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 传递异常信息
        request.setAttribute("filterError", new TokenException());
        // 指定处理该请求的处理器
        request.getRequestDispatcher(CommonName.ERROR_CONTROLLER_PATH).forward(request, response);
    }
}
